<?php
namespace app\controllers;


use app\common\corelib\CacheHelper;
use app\common\corelib\LocalUpload;
use app\common\HttpCurl;
use app\logic\CategoryLogic;
use app\models\Category;
use yii;

class CategoryController extends BackendController
{
    const LIMIT=30;


    public function actionIndex()
    {
        /*if(!CacheHelper::get('local_first_category_temp') || !CacheHelper::get('local_second_category_temp')){
            set_time_limit(0);
            $result = HttpCurl::post("yanxuan.item.id.batch.get");
            //$result = explode(',',$result);
            $total_can_buy = count($result);
            $total_page = ceil($total_can_buy/self::LIMIT);
            file_put_contents(date("Ymd")."request.txt", "总共$total_page 次"." 日期：".date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
            $local_goods = [];
            for($i=1;$i<=$total_page;$i++){
                $httpcurl = new HttpCurl();
                $offset = self::LIMIT*($i-1);
                $spuids = array_slice($result,$offset,self::LIMIT);
                file_put_contents(date("Ymd")."request.txt", "$i:".implode(',',$spuids)." 日期：".date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
                $goods_list = $httpcurl->rollpost("yanxuan.item.batch.get",['itemIds'=>implode(',',$spuids)]);
                foreach($goods_list AS $key=>$value){
                    $local_goods[] = $value;
                }
                sleep(1);
            }
            $local_first_category = CacheHelper::get('local_first_category_temp');
            if(!$local_first_category)
                $local_first_category = [];
            $local_second_category = CacheHelper::get('local_second_category_temp');
            if(!$local_second_category)
                $local_second_category = [];
            $catrgoryLogic = new CategoryLogic;
            $need_update_first = true;
            $need_update_second = true;


            foreach($local_goods AS $k=>$v){
                foreach($v['categoryPathList'] AS $ke=>$va){
                    if(isset($va[0])) {
                        if (!in_array($va[0]['name'], $local_first_category)) {
                            $local_first_category[] = $va[0]['name'];
                            $category_id = $catrgoryLogic->addCategory(0, 1, $va[0]['name'], 0);
                            $need_update_first &= false;
                            if(isset($va[1])){
                                if(!in_array($va[1]['name'],$local_second_category)){
                                    $local_second_category[] = $va[1]['name'];
                                    $catrgoryLogic->addCategory($category_id,2,$va[1]['name'],0);
                                    $need_update_second &= false;
                                }
                            }
                        }

                    }

                }
            }
            if(!$need_update_first)
                CacheHelper::set('local_first_category_temp',$local_first_category);
            if(!$need_update_second)
                CacheHelper::set('local_second_category_temp',$local_second_category);
        }*/
        $categoryLogic = new CategoryLogic();

        $httpcurl = new HttpCurl();
        $result = $httpcurl->rollpost("yanxuan.item.category.get");
        foreach($result AS $key=>$value){
            if($value['id']=='1000000000000')
                continue;
            $category = $categoryLogic->getCategoryByYx($value['id']);
            if($category){
                $category->category_name = $value['name'];
            }else{
                $category = new Category();
                $category->yx_category_id = $value['id'];
                //$category->parent_id = 0;
                //$category->level = 1;
                $category->category_name = $value['name'];
            }
            $category->save();
            if($value['subCateList']){
                foreach($value['subCateList'] AS $k=>$v){
                    $subcategory = $categoryLogic->getCategoryByYx($v['id']);
                    if($subcategory){
                        $subcategory->category_name = $v['name'];
                    }else{
                        $subcategory = new Category();
                        $subcategory->yx_category_id = $v['id'];
                        $subcategory->parent_id = $category->category_id;
                        $subcategory->level = 2;
                        $subcategory->category_name = $v['name'];
                        //$category->category_sort = 0;
                    }
                    $subcategory->save();
                }
            }


        }

        $query = Yii::$app->request->get('form', []);
        $page = Yii::$app->request->get('page', 1);

        $query['parent_id'] = 0;
        $query['level'] = 1;
        $this->data['breadcrumbs'] = '类目管理';

        /*unset($local_first_category);
        unset($local_second_category);
        unset($local_goods);*/

        return $this->render('index', [
            'category' => $categoryLogic->getCategory($query, $page),
            'query' => $query
        ]);
    }

    public function actionSubIndex(){
        $id = Yii::$app->request->post('category_id', 0);
        $categoryLogic = new CategoryLogic();
        echo json_encode($categoryLogic->getSubCategory($id));
    }

    public function actionEdit()
    {
        $categoryLogic = new CategoryLogic();
        if(!Yii::$app->request->post()){
            $id = Yii::$app->request->get('category_id');
            $category = $categoryLogic->getById($id);
            $this->data['breadcrumbs'] = ['类目管理' => U('category/index'), $category['category_name'] => '', '更新' => ''];
            if(file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'web'.$category['category_pic'])){
                $pic = $category['category_pic'];
            }else{
                $pic = '';
            }
            return $this->render('edit', [
                'category' => $category,
                'pic' => $pic,
                'theme' => '/assets/',
                'actionUrl' => U('category/edit'),
            ]);
        }else{
            $params = Yii::$app->request->post('form');
            $id = Yii::$app->request->post('category_id');
            if($_FILES['pic']['name']){
                LocalUpload::go_upload($_FILES['pic']);
                $uploadresult = '/uploads/'.LocalUpload::$filedir.'/'.LocalUpload::$filename;
                $thumbs = LocalUpload::thumbs(100,100);
            }else{
                $uploadresult = '';
            }

            $logicRes = $categoryLogic->editCategoryById($id, $params,$uploadresult);
            if ($logicRes) {
                Yii::$app->getSession()->setFlash('success','更新类目成功');
                jump('category/index');
            } else {
                Yii::$app->getSession()->setFlash('error','更新类目失败');
                $this->goBack(Yii::$app->request->referrer);
            }
        }

    }




}
